package com.fsnbigdata.web;
import com.fsnbigdata.domain.AnimalConservation;
import com.fsnbigdata.domain.Ecosystem;
import com.fsnbigdata.domain.Specimen;
import com.fsnbigdata.domain.dto.NamingPair;
import com.fsnbigdata.domain.query.AnimalConservationQueryDslBinder;
import com.fsnbigdata.domain.query.EcosystemQueryDslBinder;
import com.fsnbigdata.enums.ResultEnum;
import com.fsnbigdata.exception.ParamException;
import com.fsnbigdata.util.ReflectUtil;
import com.fsnbigdata.util.SortTools;
import com.querydsl.core.types.Predicate;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType;
import org.springframework.roo.addon.web.mvc.controller.annotations.RooController;
import org.springframework.roo.addon.web.mvc.controller.annotations.responses.json.RooJSON;
import com.fsnbigdata.service.api.EcosystemService;
import io.springlets.data.domain.GlobalSearch;

import java.lang.reflect.Method;
import java.security.Principal;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
import springfox.documentation.annotations.ApiIgnore;

/**
 * = EcosystemsCollectionJsonController
 *
 * TODO Auto-generated class documentation
 *
 */
@RooController(entity = Ecosystem.class, pathPrefix = "/api", type = ControllerType.COLLECTION)
@RooJSON
@RestController
@RequestMapping(value = "/api/ecosystems", name = "EcosystemsCollectionJsonController", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "Ecosystem", description = "生态环境" )
public class EcosystemsCollectionJsonController {

    /**
     * TODO Auto-generated attribute documentation
     *
     */
    private EcosystemService ecosystemService;

    /**
     * TODO Auto-generated constructor documentation
     *
     * @param ecosystemService
     */
    @Autowired
    public EcosystemsCollectionJsonController(EcosystemService ecosystemService) {
        this.ecosystemService = ecosystemService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @return EcosystemService
     */
    public EcosystemService getEcosystemService() {
        return ecosystemService;
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param ecosystemService
     */
    public void setEcosystemService(EcosystemService ecosystemService) {
        this.ecosystemService = ecosystemService;
    }

    @GetMapping(name = "index", value = "index")
    public ResponseEntity<List<NamingPair>> category(
        @ApiParam @RequestParam(required = false) String initial) {
        List<NamingPair> namingPairs = getEcosystemService().findAllByInitial(initial);
        return ResponseEntity.ok(namingPairs);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param query
     * @param pageable
     * @return ResponseEntity
     */
    @GetMapping(name = "search", value = "search")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Ecosystem>> search(
            @ApiParam @RequestParam(required = false) String query,
            Pageable pageable,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String value) {
        GlobalSearch globalSearch = StringUtils.isNotBlank(query) ? new GlobalSearch(query, false) : null;
        Page<Ecosystem> ecosystems=null;
        if (StringUtils.isNotEmpty(name)&&StringUtils.isNotEmpty(value)){
            Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(),SortTools.basicSort(name,value));
            ecosystems = getEcosystemService().findAll(globalSearch, pageable1);
        }else{
            ecosystems = getEcosystemService().findAll(globalSearch, pageable);
        }
        return ResponseEntity.ok(ecosystems);
    }

    /**
     *
     * @param predicate
     * @param pageable
     * @return
     */
    @GetMapping(name = "search", value = "advanceSearch")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Ecosystem>> advanceSearch(
            @ApiParam @QuerydslPredicate(root = Ecosystem.class, bindings = EcosystemQueryDslBinder.class) Predicate predicate,
            Pageable pageable) {
        Page<Ecosystem> ecosystems = getEcosystemService().search(predicate, pageable);
        return ResponseEntity.ok(ecosystems);
    }

    /**
     * 查询部分信息
     * @return
     */
    @GetMapping(name = "search", value = "query")
    public List<List<Ecosystem>> query() {
        return getEcosystemService().findByType(  );
    }

    /**
     * 根据id查询详情
     * @param request
     * @return
     */
    @GetMapping(name = "find" , value="find")
    public Ecosystem findById(HttpServletRequest request){
        return getEcosystemService().findOne(Long.parseLong(request.getParameter("id")));
    }

    /**
     * 自定义搜索
     * @param
     * @param
     * @param pageable
     * @return
     */
    @GetMapping(name = "search", value = "customSearch")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public List getList(HttpServletRequest request,Pageable pageable){
        String name = request.getParameter("name");//关键字
        String content = request.getParameter("content");//desc或asc
        String value = request.getParameter("value");//字段名称
        String type = request.getParameter("type");//类型
        String administrativeLocation = request.getParameter( "administrativeLocation" );
        String currentLevel = request.getParameter( "currentLevel" );
        String createDate = request.getParameter( "createDate" );
        String administrativeDepartment = request.getParameter( "administrativeDepartment" );

        if (StringUtils.isNotEmpty(content)&&StringUtils.isNotEmpty(value)){
            Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(),SortTools.basicSort(content,value));
            return ecosystemService.queryByKey(name,administrativeLocation,currentLevel, createDate,administrativeDepartment,type,pageable1);
        }else{
            return ecosystemService.queryByKey(name,administrativeLocation,currentLevel, createDate,administrativeDepartment,type,pageable);
        }
    }
    /**
     * 根据id 降序排序
     */
    @GetMapping(name = "search", value = "sortByIdAndDesc")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Ecosystem>> sortByIdAndDesc(
            @ApiParam @QuerydslPredicate(root = Ecosystem.class, bindings = EcosystemQueryDslBinder.class) Predicate predicate,
            Pageable pageable) {
        Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(),SortTools.basicSort("DESC","id"));
        Page<Ecosystem> ecosystems=getEcosystemService().search(predicate, pageable1);
        return ResponseEntity.ok(ecosystems);
    }
    /**
     * 根据id 升序排序
     */

    @GetMapping(name = "search", value = "sortByIdAndAsc")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Ecosystem>> sortByIdAndAsc(
            @ApiParam @QuerydslPredicate(root = Ecosystem.class, bindings = EcosystemQueryDslBinder.class) Predicate predicate,
            Pageable pageable) {
        Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(), SortTools.basicSort("ASC","id"));
        Page<Ecosystem> ecosystems=getEcosystemService().search(predicate, pageable1);
        return ResponseEntity.ok(ecosystems);
    }

    /**
     * 根据 collectDate 升序排序
     *
     */
    @GetMapping(name = "search", value = "sortByCreateDateDesc")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Ecosystem>> sortByCollectDateDesc(
            @ApiParam @QuerydslPredicate(root = Ecosystem.class, bindings = EcosystemQueryDslBinder.class) Predicate predicate,
            Pageable pageable) {
        Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(),SortTools.basicSort("DESC","createDate"));
        Page<Ecosystem> ecosystems=getEcosystemService().search(predicate, pageable1);
        return ResponseEntity.ok(ecosystems);
    }
    /**
     * 根据 collectDate 升序排序
     *
     */
    @GetMapping(name = "search", value = "sortByCreateDateAsc")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public ResponseEntity<Page<Ecosystem>> sortByCollectDateAsc(
            @ApiParam @QuerydslPredicate(root = Ecosystem.class, bindings = EcosystemQueryDslBinder.class) Predicate predicate,
            Pageable pageable) {
        Pageable pageable1=new PageRequest(pageable.getPageNumber(),pageable.getPageSize(),SortTools.basicSort("ASC","createDate"));
        Page<Ecosystem> ecosystems=getEcosystemService().search(predicate, pageable1);
        return ResponseEntity.ok(ecosystems);
    }
    /**
     * TODO Auto-generated method documentation
     *
     * @param query
     * @param pageable
     * @return ResponseEntity
     */
    @GetMapping(name = "list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    @PreAuthorize("hasRole('DB_ECOSYSTEM')")
    public ResponseEntity<Page<Ecosystem>> list(
            Authentication authentication,
            @ApiParam @RequestParam(required = false) String query,
            Pageable pageable) {
        GlobalSearch globalSearch = StringUtils.isNotBlank(query) ? new GlobalSearch(query, false) : null;
        Page<Ecosystem> ecosystems = null;
        List<String> authorities = authentication.getAuthorities().stream().map(it -> it.getAuthority()).collect(Collectors.toList());
        if(!authorities.contains("ROLE_USER_ADMIN")){
            ecosystems = getEcosystemService().findAll(globalSearch, pageable, authentication.getName());
        }else{
            ecosystems = getEcosystemService().findAll(globalSearch, pageable);
        }
        return ResponseEntity.ok(ecosystems);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @return UriComponents
     */
    public static UriComponents listURI() {
        return MvcUriComponentsBuilder.fromMethodCall(MvcUriComponentsBuilder.on(EcosystemsCollectionJsonController.class).list(null,null, null)).build().encode();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param ecosystem
     * @param result
     * @return ResponseEntity
     */
    @PostMapping(name = "create")
    @PreAuthorize("hasRole('DB_ECOSYSTEM')")
    @ApiOperation(value = "",notes = "save")
    public ResponseEntity<?> create(
            @Valid @RequestBody Ecosystem ecosystem,
            BindingResult result,
            Principal principal) throws Exception {
        if (ecosystem.getId() != null || ecosystem.getVersion() != null) {
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        }
        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }

        ecosystem.setCreator(principal.getName());

        ecosystem.getImages().forEach(it -> it.setEcosystem(ecosystem));

        Ecosystem newEcosystem = getEcosystemService().save(ecosystem);
        UriComponents showURI = EcosystemsItemJsonController.showURI(newEcosystem);

        Class<?> clazz = EcosystemsCollectionJsonController.class;
        Method method = clazz.getMethod("create", ReflectUtil.getPeremeterClass(clazz, "create"));
        ReflectUtil.setAnnotationOn(method,"新增生态库，名称："+newEcosystem.getName());

        //return ResponseEntity.created(showURI.toUri()).build();
        return ResponseEntity.ok(newEcosystem);
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param ecosystems
     * @param result
     * @return ResponseEntity
     */
    @PostMapping(value = "/batch", name = "createBatch")
    @PreAuthorize("hasRole('DB_ECOSYSTEM')")
    @ApiIgnore
    public ResponseEntity<?> createBatch(@Valid @RequestBody Collection<Ecosystem> ecosystems, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
        }

        ecosystems.forEach(ecosystem -> ecosystem.getImages().forEach(it -> it.setEcosystem(ecosystem)));
        getEcosystemService().save(ecosystems);
        return ResponseEntity.created(listURI().toUri()).build();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param ecosystems
     * @param result
     * @return ResponseEntity
     */
    @PutMapping(value = "/batch", name = "updateBatch")
    @PreAuthorize("hasRole('DB_ECOSYSTEM')")
    @ApiIgnore
    public ResponseEntity<?> updateBatch(@Valid @RequestBody Collection<Ecosystem> ecosystems, BindingResult result) {
        if (result.hasErrors()) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
        }

        ecosystems.forEach(ecosystem -> ecosystem.getImages().forEach(it -> it.setEcosystem(ecosystem)));

        getEcosystemService().save(ecosystems);
        return ResponseEntity.ok().build();
    }

    /**
     * TODO Auto-generated method documentation
     *
     * @param ids
     * @return ResponseEntity
     */
    @DeleteMapping(value = "/batch/{ids}", name = "deleteBatch")
    @PreAuthorize("hasRole('DB_ECOSYSTEM')")
    @ApiIgnore
    public ResponseEntity<?> deleteBatch(@PathVariable("ids") Collection<Long> ids) {
        getEcosystemService().delete(ids);
        return ResponseEntity.ok().build();
    }
}
